/* eslint-disable no-console */

import config from './config';
import { environments } from './constants';

const chalk = require('chalk');
const ip = require('ip');
const path = require('path');
const winston = require('winston');

const divider = chalk.gray('\n-----------------------------------');
const serverLogFile = path.join(__dirname, '../logs/server.log');
const dbLogFile = path.join(__dirname, '../logs/db.log');


const logger = new (winston.Logger)({
  transports: [
    new (winston.transports.File)({
      name: 'server-text',
      filename: serverLogFile,
      json: false,
    }),
    new (winston.transports.Console)({
      logstash: config.env !== environments.DEV.value,
      stringify: config.env !== environments.DEV.value,
    }),
  ],
});

const dbLogger = new (winston.Logger)({
  transports: [
    new (winston.transports.File)({
      name: 'db-text',
      filename: dbLogFile,
      json: false,
    }),
  ],
});

if (config.env !== environments.DEV.value) {
  dbLogger.add(winston.transports.Console, {
    logstash: true,
    stringify: true,
  });
}

// logger.json = (...rest) => {
//   function syntaxHighlight(json) {
//     if (typeof json !== 'string') {
//       return JSON.stringify(json, undefined, 2);
//     }
//     return json;
//   }
//   const result = rest.map(obj => syntaxHighlight(obj));
//   console.log(...result);
//   return result;
// };
// logger.highlight = (...rest) => {
//   console.log(chalk.yellow('=============================='));
//   console.log(...rest);
// };

logger.appStarted = (port, tunnelStarted, serverName) => {
  console.log(`${serverName || 'Server'} started ${chalk.green('✓')}`);

  // If the tunnel started, log that and the URL it's available at
  if (tunnelStarted) {
    console.log(`Tunnel initialised ${chalk.green('✓')}`);
  }

  console.log(`
${chalk.bold('Access URLs:')}${divider}
Localhost: ${chalk.magenta(`http://localhost:${port}`)}
      LAN: ${chalk.magenta(`http://${ip.address()}:${port}`) +
  (tunnelStarted ? `\n    Proxy: ${chalk.magenta(tunnelStarted)}` : '')}${divider}
${chalk.blue(`Press ${chalk.italic('CTRL-C')} to stop`)}
    `);
};

module.exports = {
  logger,
  dbLogger,
};
